from fastapi import APIRouter, Request, Cookie, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from typing import Optional

# 导入国际化支持
from utils.i18n import get_text, get_translated_categories, get_translated_tools

# 导入工具和分类定义
from api.tools_config import tools, tool_categories, supported_languages

# 导入文档工具函数
from api.doc_tools import get_doc_tools

# 导入配置中的API_PDF
from api.config import API_PDF

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 创建路由
router = APIRouter()

# 添加语言切换路由
@router.get("/set-language/{lang_code}")
async def set_language(lang_code: str, response: Response, request: Request):
    # 验证语言代码
    if lang_code not in [lang["code"] for lang in supported_languages]:
        lang_code = "zh"  # 默认使用中文
    
    # 设置语言Cookie
    response = RedirectResponse(request.headers.get("referer", "/"))
    response.set_cookie(key="language", value=lang_code, max_age=31536000)  # 一年有效期
    
    return response

@router.get("/", response_class=HTMLResponse)
async def home(request: Request, language: Optional[str] = Cookie(None)):
    # 如果未设置语言，默认使用中文
    if not language or language not in [lang["code"] for lang in supported_languages]:
        language = "zh"
    
    # 获取文档工具列表
    doc_tools = get_doc_tools()
    
    # 合并工具列表
    all_tools = tools + doc_tools
    
    # 翻译工具分类和工具列表
    translated_categories = get_translated_categories(tool_categories, language)
    translated_tools = get_translated_tools(all_tools, language)
    
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request, 
            "categories": translated_categories, 
            "tools": translated_tools,
            "current_language": language,
            "supported_languages": supported_languages,
            "app_title": get_text("app_title", language),
            "app_description": get_text("app_description", language),
            "welcome_title": get_text("welcome_title", language),
            "welcome_text": get_text("welcome_text", language),
            "search_placeholder": get_text("search_placeholder", language),
            "copyright": get_text("copyright", language),
            "use_tool": get_text("use_tool", language),
            "view_doc": get_text("view_doc", language)
        }
    )

@router.get("/tools/{tool_id}", response_class=HTMLResponse)
async def tool_page(request: Request, tool_id: str, language: Optional[str] = Cookie(None)):
    # 如果未设置语言，默认使用中文
    if not language or language not in [lang["code"] for lang in supported_languages]:
        language = "zh"
    
    # 查找对应的工具
    # 获取文档工具列表
    doc_tools = get_doc_tools()
    # 合并工具列表
    all_tools = tools + doc_tools
    tool = next((t for t in all_tools if t["id"] == tool_id), None)
    if not tool:
        return templates.TemplateResponse("404.html", {"request": request})
    
    # 翻译工具信息和分类
    translated_tool = get_translated_tools([tool], language)[0]
    translated_categories = get_translated_categories(tool_categories, language)
    
    # 特殊处理 stirling-pdf 工具，传递外部URL
    if tool_id == "stirling-pdf":
        context = {
            "request": request, 
            "tool": translated_tool, 
            "categories": translated_categories,
            "current_language": language,
            "supported_languages": supported_languages,
            "back_to_home": get_text("back_to_home", language),
            "back": get_text("back", language),
            "app_title": get_text("app_title", language),
            "app_description": get_text("app_description", language),
            "copyright": get_text("copyright", language),
            "get_text": get_text,
            "tool_external_url": API_PDF  # 传递 Stirling PDF 的外部 URL
        }
        return templates.TemplateResponse(f"tools/{tool_id}.html", context)

    # 返回对应的工具页面
    return templates.TemplateResponse(
        f"tools/{tool_id}.html",
        {
            "request": request, 
            "tool": translated_tool, 
            "categories": translated_categories,
            "current_language": language,
            "supported_languages": supported_languages,
            "back_to_home": get_text("back_to_home", language),
            "back": get_text("back", language),
            "app_title": get_text("app_title", language),
            "app_description": get_text("app_description", language),
            "copyright": get_text("copyright", language),
            # 添加get_text函数，使模板可以直接调用
            "get_text": get_text,
            
            # 通用按钮和操作
            "copy": get_text("copy", language),
            "clear": get_text("clear", language),
            "convert": get_text("convert", language),
            "result": get_text("result", language),
            "search": get_text("search", language),
            "loading": get_text("loading", language),
            "download": get_text("download", language),
            "generate": get_text("generate", language),
            "preview": get_text("preview", language),
            
            # 时间戳转换工具
            "seconds": get_text("seconds", language),
            "milliseconds": get_text("milliseconds", language),
            "pause": get_text("pause", language),
            "resume": get_text("resume", language),
            "enter_timestamp": get_text("enter_timestamp", language),
            "current_timestamp": get_text("current_timestamp", language),
            "toggle_unit": get_text("toggle_unit", language),
            "timestamp_to_date": get_text("timestamp_to_date", language),
            "date_to_timestamp": get_text("date_to_timestamp", language),
            "timestamp": get_text("timestamp", language),
            "timestamp_type": get_text("timestamp_type", language),
            "timezone": get_text("timezone", language),
            "datetime": get_text("datetime", language),
            
            # 二维码生成器
            "basic_settings": get_text("basic_settings", language),
            "qr_content": get_text("qr_content", language),
            "size_pixels": get_text("size_pixels", language),
            "margin_pixels": get_text("margin_pixels", language),
            "dot_style": get_text("dot_style", language),
            "square": get_text("square", language),
            "round": get_text("round", language),
            "color_settings": get_text("color_settings", language),
            "background_color": get_text("background_color", language),
            "foreground_color": get_text("foreground_color", language),
            "eye_color": get_text("eye_color", language),
            "eye_radius": get_text("eye_radius", language),
            "preset_colors": get_text("preset_colors", language),
            "preset_classic": get_text("preset_classic", language),
            "preset_business": get_text("preset_business", language),
            "preset_red": get_text("preset_red", language),
            "preset_green": get_text("preset_green", language),
            "preset_tech": get_text("preset_tech", language),
            
            # ICO图标生成器
            "upload_image": get_text("upload_image", language),
            "remove": get_text("remove", language),
            "supported_formats": get_text("supported_formats", language),
            "image_preview": get_text("image_preview", language),
            "icon_size": get_text("icon_size", language),
            "common_sizes": get_text("common_sizes", language),
            "corner_radius": get_text("corner_radius", language),
            "preset_sizes": get_text("preset_sizes", language),
            "preset_corners": get_text("preset_corners", language),
            "no_corner": get_text("no_corner", language),
            "slight_corner": get_text("slight_corner", language),
            "rounded_corner": get_text("rounded_corner", language),
            "circle": get_text("circle", language),
            "generate_icon": get_text("generate_icon", language),
            "download_icon": get_text("download_icon", language),
            "icon_preview": get_text("icon_preview", language),
            "please_upload": get_text("please_upload", language),
            "generating": get_text("generating", language),
            
            # 颜色选择器
            "color_picker": get_text("color_picker", language),
            "select_color": get_text("select_color", language),
            "color_preview": get_text("color_preview", language),
            "complementary_color": get_text("complementary_color", language),
            "color_palette": get_text("color_palette", language),
            "monochromatic": get_text("monochromatic", language),
            "analogous": get_text("analogous", language),
            "triadic": get_text("triadic", language),
            "tetradic": get_text("tetradic", language),
            
            # 摄影参数计算器
            "exposure_calculator": get_text("exposure_calculator", language),
            "aperture": get_text("aperture", language),
            "shutter_speed": get_text("shutter_speed", language),
            "iso": get_text("iso", language),
            "calculate_ev": get_text("calculate_ev", language),
            "exposure_value": get_text("exposure_value", language),
            "dof_calculator": get_text("dof_calculator", language),
            "focal_length": get_text("focal_length", language),
            "focus_distance": get_text("focus_distance", language),
            "sensor_size": get_text("sensor_size", language),
            "calculate_dof": get_text("calculate_dof", language),
            "dof_result": get_text("dof_result", language),
            "near_limit": get_text("near_limit", language),
            "far_limit": get_text("far_limit", language),
            "total_dof": get_text("total_dof", language),
            "hyperfocal": get_text("hyperfocal", language),

            # PDF Editor
            "previous_page": get_text("previous_page", language),
            "next_page": get_text("next_page", language),
            "page": get_text("page", language),
            "editing_tools": get_text("editing_tools", language),
            "add_text": get_text("add_text", language),
            "enter_text_here": get_text("enter_text_here", language),
            "font_size": get_text("font_size", language),
            "color": get_text("color", language),
            "add_image": get_text("add_image", language),
            "draw_rectangle": get_text("draw_rectangle", language),
            "draw_line": get_text("draw_line", language),
            "shape_line_color": get_text("shape_line_color", language),
            "line_width": get_text("line_width", language),
            "save_pdf": get_text("save_pdf", language),
            
            # 延迟摄影计算器
            "timelapse_calculator": get_text("timelapse_calculator", language),
            "real_duration": get_text("real_duration", language),
            "hours": get_text("hours", language),
            "minutes": get_text("minutes", language),
            "real_duration_desc": get_text("real_duration_desc", language),
            "video_duration": get_text("video_duration", language),
            "video_duration_desc": get_text("video_duration_desc", language),
            "fps": get_text("fps", language),
            "fps_desc": get_text("fps_desc", language),
            "calculate_params": get_text("calculate_params", language),
            "calculation_result": get_text("calculation_result", language),
            "total_frames": get_text("total_frames", language),
            "interval_seconds": get_text("interval_seconds", language),
            "camera_settings": get_text("camera_settings", language),
            "timelapse_tips": get_text("timelapse_tips", language),
            "stability": get_text("stability", language),
            "stability_desc": get_text("stability_desc", language),
            "battery": get_text("battery", language),
            "battery_desc": get_text("battery_desc", language),
            "storage": get_text("storage", language),
            "storage_desc": get_text("storage_desc", language),
            "manual_settings": get_text("manual_settings", language),
            "manual_settings_desc": get_text("manual_settings_desc", language),
            "aperture_priority": get_text("aperture_priority", language),
            "aperture_priority_desc": get_text("aperture_priority_desc", language),
            "focus": get_text("focus", language),
            "focus_desc": get_text("focus_desc", language),
            "common_subjects": get_text("common_subjects", language),
            "subject": get_text("subject", language),
            "suggested_interval": get_text("suggested_interval", language),
            "clouds": get_text("clouds", language),
            "crowd": get_text("crowd", language),
            "sunrise": get_text("sunrise", language),
            "stars": get_text("stars", language),
            "flowers": get_text("flowers", language),
            
            # 摄影天气查看
            "check_location_weather": get_text("check_location_weather", language),
            "location": get_text("location", language),
            "use_current_location": get_text("use_current_location", language),
            "location_example": get_text("location_example", language),
            "date": get_text("date", language),
            "check_weather": get_text("check_weather", language),
            "photo_suggestions": get_text("photo_suggestions", language),
            "getting_weather": get_text("getting_weather", language),
            "sunrise_time": get_text("sunrise_time", language),
            "sunset_time": get_text("sunset_time", language),
            "wind_speed": get_text("wind_speed", language),
            "humidity": get_text("humidity", language),
            "golden_hour": get_text("golden_hour", language),
            "morning": get_text("morning", language),
            "evening": get_text("evening", language),
            "blue_hour": get_text("blue_hour", language),
            "weather_forecast": get_text("weather_forecast", language),
            "hourly_forecast": get_text("hourly_forecast", language),
            "time": get_text("time", language),
            "temp": get_text("temp", language),
            "conditions": get_text("conditions", language)
        }
    )

# 添加文档页面路由
@router.get("/doc/{doc_id}", response_class=HTMLResponse)
async def doc_page(request: Request, doc_id: str, language: Optional[str] = Cookie(None)):
    # 如果未设置语言，默认使用中文
    if not language or language not in [lang["code"] for lang in supported_languages]:
        language = "zh"
    
    # 创建一个tool变量，以满足base_tool.html模板的需求
    tool = {
        "name": "文档查看" if language == "zh" else "Documentation",
        "description": "查看详细文档说明" if language == "zh" else "View detailed documentation",
        "icon": "book",
        "categories": ["documentation"]
    }
    
    # 翻译工具分类
    translated_categories = get_translated_categories(tool_categories, language)
    
    return templates.TemplateResponse(
        "tools/documentation.html",
        {
            "request": request, 
            "categories": translated_categories, 
            "doc_id": doc_id, 
            "tool": tool,
            "current_language": language,
            "supported_languages": supported_languages,
            "back_to_home": get_text("back_to_home", language),
            "back": get_text("back", language),
            "app_title": get_text("app_title", language),
            "app_description": get_text("app_description", language),
            "copyright": get_text("copyright", language)
        }
    )

# 添加书签页面路由
@router.get("/tools/bookmarks", response_class=HTMLResponse)
async def bookmarks_page(request: Request, language: Optional[str] = Cookie(None)):
    # 如果未设置语言，默认使用中文
    if not language or language not in [lang["code"] for lang in supported_languages]:
        language = "zh"
    
    # 查找对应的工具
    tool = next((t for t in tools if t["id"] == "bookmarks"), None)
    if not tool:
        return templates.TemplateResponse("404.html", {"request": request})
    
    # 翻译工具信息和分类
    translated_tool = get_translated_tools([tool], language)[0]
    translated_categories = get_translated_categories(tool_categories, language)
    
    # 返回书签页面
    return templates.TemplateResponse(
        "tools/bookmarks.html",
        {
            "request": request, 
            "tool": translated_tool, 
            "categories": translated_categories,
            "current_language": language,
            "supported_languages": supported_languages,
            "back_to_home": get_text("back_to_home", language),
            "back": get_text("back", language),
            "app_title": get_text("app_title", language),
            "app_description": get_text("app_description", language),
            "copyright": get_text("copyright", language),
            # 添加get_text函数，使模板可以直接调用
            "get_text": get_text
        }
    )

# API路由示例
@router.get("/api/tools")
async def get_tools(category: str = None):
    if category and category != "all":
        filtered_tools = [t for t in tools if category in t["categories"]]
        return {"tools": filtered_tools}
    return {"tools": tools}

from api.config import API_URL, API_TOKEN
@router.get("/api/get_sensitive_info")
async def get_sensitive_info():
    return {
        'api_url': API_URL,
        'api_token': API_TOKEN
    }